package com.tyl.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.tyl.dao.BaseDao;
import com.tyl.pojo.Role;
import com.tyl.pojo.User;
import com.tyl.service.role.RoleService;
import com.tyl.service.role.RoleServiceImpl;
import com.tyl.service.user.UserService;
import com.tyl.service.user.UserServiceImpl;
import com.tyl.utils.Constants;
import com.tyl.utils.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.SimpleTimeZone;

//修改密码
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("method");
        if (method.equals("savepwd")&&method!=null){//修改密码
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify")&&method!=null){//旧密码验证
            this.pwdModify(req,resp);
        }else if(method.equals("query")&&method!=null){//查询列表三条线核心
            this.query(req,resp);
        }else if(method.equals("add")&&method!=null){//添加用户
            this.add(req,resp);
        }else if(method.equals("ucexist")&&method!=null){//判断用户是否可以重复，是否可被添加
            this.userCodeExist(req,resp);
        }else if(method.equals("getrolelist")&&method!=null){//获取角色列表，1,2,3
            this.getRoleList(req,resp);
        }else if(method.equals("deluser")&&method!=null){//删除用户
            this.deluser(req,resp);
        }else if(method.equals("view")&&method!=null){//查看用户信息
            this.getUserId(req,resp,"userview.jsp");
        }else if(method.equals("modify")&&method!=null){//进图修改用户信息
            this.getUserId(req,resp,"usermodify.jsp");
        }else if(method.equals("modifyexe")&&method!=null){
            this.userModify(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 方法复用修改密码
     * **/
    public void  updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session中拿到用户
        Object o=req.getSession().getAttribute(Constants.USER_SESSION);
        //拿到新密码
        String newPassword=req.getParameter("newpassword");
        boolean flag=false;
        if(o!=null&&newPassword!=null){
            UserService userService=new UserServiceImpl();
            //执行修改密码
            flag = userService.updatePwd(((User) o).getId(), newPassword);
            if (flag){
                req.setAttribute("message","修改密码成功，请退出使用新密码登录！");
                //移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
                req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
            }else{
                req.setAttribute("message","修改密码失败！");
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }
    }
    /**
     * 旧密码验证，从session中取出来密码
     * **/
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从session中获取用户
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        // 拿到旧密码
        String oldPassword = req.getParameter("oldpassword");

        HashMap<String, String> map = new HashMap<String, String>();
        if(o==null){//session失效了
            map.put("resule","sessionerror");
        }else if(oldPassword.equals(null)){//旧密码输入为空
            map.put("resule","error");
        }else{
            String userPassword = ((User) o).getUserPassword();//从session中获取密码
            if(userPassword.equals(oldPassword)){
                map.put("result","true");
            }else{
                map.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));//map转为jason格式
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户列表、分页、角色列表
     * **/
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        //查询列表传入的值
        String queryUserName = req.getParameter("queryname");//从前端获取用户名
        String tempQueryUserRole = req.getParameter("queryUserRole");//从前端获取用角色
        String PageIndex = req.getParameter("pageIndex");//从前端获取当前页
        int queryUserRole=0;

        //获取用户列表
        UserService userService=new UserServiceImpl();
        List<User> userList=null;


        //第一次请求肯定是第一页，页面固定大小
        int pageSize=5;
        int currentPageNo=1;

        if(queryUserName==null){
            queryUserName="";
        }
        if(tempQueryUserRole!=null&&!tempQueryUserRole.equals("")){
            queryUserRole=Integer.parseInt(tempQueryUserRole);//给查询赋值，0,1,2,3
        }
        if (PageIndex!=null){
            currentPageNo=Integer.parseInt(PageIndex);
        }
        //获取用户总数
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        int totalPageCount =((int)(totalCount/pageSize)+1);//最大页数
        //如果页面小于1，则页面改为1
        if (totalPageCount<1){
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }

        //获取用户列表展示

        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);

        RoleService roleService=new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);

        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);

        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断用户是否存在
     * **/

    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String userCode=req.getParameter("userCode");
        HashMap<String, String> o = new HashMap<String, String>();
        if(userCode == null || userCode.equals("")){
            o.put("userCode", "exist");
        }else {
            UserService userService=new UserServiceImpl();
            User user = userService.getUserCode(userCode);
            if(user!=null){
                o.put("userCode", "exist");
            }else{
                o.put("userCode", "notexist");
            }
        }
        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = resp.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(o));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }

    /**
     * 获取角色列表
     * **/
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    /**
     * 添加用户
     * **/
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        System.out.println(user.toString());
        UserService userService = new UserServiceImpl();
        boolean add = userService.addUser(user);
        if (add) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }


    /**
     * 删除用户
     * **/
    public void deluser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String user = req.getParameter("uid");
        Integer deleteId=0;
        int flag=0;
        try {
            deleteId=Integer.parseInt(user);
        } catch (NumberFormatException e) {
            deleteId=0;
        }
        HashMap<String, String> o = new HashMap<String, String>();
        if (deleteId<=0){
            o.put("delResult","notexist");
        }else{
            try {
                UserService userService=new UserServiceImpl();
                flag = userService.deleteByUserId(deleteId);
                if (flag>0){
                    o.put("delResult","true");
                }else{
                    o.put("delResult","false");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(o));
        writer.flush();
        writer.close();
    }

    /**
     * 查看用户信息
     * **/
    public void getUserId(HttpServletRequest req, HttpServletResponse resp,String url) throws IOException, ServletException {
        String uid = req.getParameter("uid");
        User user = null;
        if (uid!=null&&!uid.equals("")){
            UserService userService=new UserServiceImpl();
            try {
                user = userService.getUserId(uid);
                req.setAttribute("user",user);
                req.getRequestDispatcher(url).forward(req,resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 修改用户
     * **/
    public  void  userModify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从前端获取到数据
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        //放到user中
        User user=new User();
        user.setId(Integer.parseInt(id));
        user.setUserName(userName);
        user.setGender(Integer.parseInt(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));

        //修改这从session中拿
        user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService=new UserServiceImpl();
        int flag=0;
        flag=userService.updateUser(user);
        if (flag>0){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            try {
                req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }

    }
}
